#include "sys.h"
#include "log.h"
#include "thread_pool.h"
#include "cJSON.h"

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

extern char **environ;
static void print_env(){
    char **env = environ;

    while(*env){
        log_trace("%s", *env);
        env++;
    }
}
static void *__task(void *arg){
    sleep(1);
    return (void *) 2;
}
static void* _task(void* arg)
{
    int level = (int)arg;
    pthread_t thid[200] = {0};
    int i = 0;
    int *ret, result = 0;

    if(level == 0){
        sleep(1);
        return (void *)1;
    }
    level--;
    for(i=0; i < 5; i++){
        result = pthread_create(&thid[i], NULL, _task, (void *)level);
        if(result != 0){
            log_error("pthread create error.%d, %s", result, strerror(result));
            continue;
        }
        log_trace("create thread level:%d, i:%d, tid:%u", level, i, thid[i]);
    }

    for(i =0; i < 5; i++){
        if(thid[i] == 0){
            continue;
        }
        log_trace("pthread join :%d, tid:%u", i, thid[i]);
        pthread_join(thid[i], (void *)&ret);
    }
    return (void *)1;
}
static void _create_thread(){
    pthread_t thid[200] = {0};
    int i =0, *ret = NULL;

    while(1){

        for(i=0; i < 1; i++){
            log_trace("create thread: %d", i);
            pthread_create(&thid[i], NULL, _task, (void *)4);
            log_trace("create thread i:%d, tid:%u", i, thid[i]);
        }

        for(i =0; i < 1; i++){
            log_trace("pthread join :%d, tid:%u", i, thid[i]);
            pthread_join(thid[i], (void *)&ret);
        }


    }
    
}
int thpool_test(int argc, char** argv)
{

    _create_thread();
    return 0;

    // thread_pool_t* tpool = thread_pool_new(1);
    // thread_pool_set_auto_extern(tpool);

    // int i = 0;
    // for (i = 0; i < 20; i++) {
    //     thread_pool_add_task(tpool, _task, NULL);
    // }
    // // thread_pool_wait(tpool);
    // // thread_pool_destroy(tpool);
    // while (1) {
    //     sleep(1000);
    // }
    // int len, i =0;
    // cJSON *cj_elem, *cj_root_arr;
    // char *json_str = "[{\"a\":1,\"b\":3},{\"a\":14,\"b\":33},{\"a\":51,\"b\":33}]";
    // cJSON *data = cJSON_Parse(json_str);
    // cJSON *new_data = cJSON_Duplicate(data, 1);
    // cJSON *root = cJSON_CreateObject();
    // cJSON_AddItemToObject(root, "Arr", data);

    // cj_root_arr = cJSON_GetObjectItem(root, "Arr");
    // len = cJSON_GetArraySize(new_data);
    // while(len--){
    //     cj_elem = cJSON_DetachItemFromArray(new_data, 0);
    //     log_debug("%s", cJSON_Print(cj_elem));
    //     cJSON_AddItemToArray(cj_root_arr, cj_elem);
    // }
    // char *root_str = cJSON_Print(root);
    // log_trace("root_str:%s", root_str);

    // char *new_data_str = cJSON_Print(new_data);
    // log_trace("new_data_str:%s", new_data_str);


    return 0;
}